const axios = require('axios')
const crypto = require('crypto')

class AIService {
  constructor() {
    this.apiUrl = 'https://api.siliconflow.cn/v1/chat/completions'
    this.apiKey = process.env.SILICONFLOW_API_KEY || 'your-api-key-here'
    this.model = 'Qwen/Qwen2.5-7B-Instruct'
    this.cache = new Map() 
  }

  async makeRequest(messages, temperature = 0.7) {
    try {
      const response = await axios.post(this.apiUrl, {
        model: this.model,
        messages,
        temperature,
        max_tokens: 1000
      }, {
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json'
        },
        timeout: 30000
      })

      return response.data.choices[0].message.content
    } catch (error) {
      console.error('AI API 请求失败:', error.message)
      throw new Error('AI 服务暂时不可用，请稍后重试')
    }
  }

  generateCacheKey(input) {
    return crypto.createHash('md5').update(JSON.stringify(input)).digest('hex')
  }

  async suggestCategory(description) {
    if (!description || !description.trim()) {
      return '其他'
    }

    const cacheKey = this.generateCacheKey({ type: 'category', description })
    
    if (this.cache.has(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    if (!this.apiKey || this.apiKey === 'your-api-key-here') {
      return this.getDefaultCategorySuggestion(description)
    }

    const messages = [
      {
        role: 'system',
        content: `你是一个智能消费分类助手。根据用户的消费描述，从以下分类中选择最合适的一个：
餐饮、交通、购物、娱乐、医疗、教育、住房、其他

请只返回分类名称，不要包含其他内容。`
      },
      {
        role: 'user',
        content: `请为以下消费描述选择合适的分类：${description}`
      }
    ]

    try {
      const result = await this.makeRequest(messages, 0.3)
      const category = result.trim()
      
      // 验证返回的分类是否有效
      const validCategories = ['餐饮', '交通', '购物', '娱乐', '医疗', '教育', '住房', '其他']
      const suggestedCategory = validCategories.find(cat => category.includes(cat)) || '其他'
      
      this.cache.set(cacheKey, suggestedCategory)
      return suggestedCategory
    } catch (error) {
      console.error('分类建议失败:', error)
      return this.getDefaultCategorySuggestion(description)
    }
  }

  async analyzeExpenses(expenses) {
    if (!expenses || expenses.length === 0) {
      return {
        insights: ['暂无消费数据可分析'],
        suggestions: ['开始记录您的日常消费以获得个性化建议']
      }
    }

    const cacheKey = this.generateCacheKey({ type: 'analysis', expenses: expenses.slice(0, 50) })
    
    if (this.cache.has(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    // 计算基础统计信息
    const totalAmount = expenses.reduce((sum, exp) => sum + exp.amount, 0)
    const avgAmount = totalAmount / expenses.length
    const categoryStats = this.calculateCategoryStats(expenses)
    const topCategories = Object.entries(categoryStats)
      .sort(([,a], [,b]) => b.total - a.total)
      .slice(0, 3)

    const messages = [
      {
        role: 'system',
        content: `你是一个专业的财务分析师。基于用户的消费数据，提供有价值的洞察和建议。
请以JSON格式返回分析结果，包含insights（洞察）和suggestions（建议）两个数组。
每个数组包含3-5个简洁明了的中文条目。`
      },
      {
        role: 'user',
        content: `请分析以下消费数据：
总消费：${totalAmount.toFixed(2)}元
平均消费：${avgAmount.toFixed(2)}元
消费记录数：${expenses.length}条
主要消费分类：${topCategories.map(([cat, stats]) => `${cat}(${stats.total.toFixed(2)}元)`).join('、')}

请提供财务洞察和节省建议。`
      }
    ]

    try {
      const result = await this.makeRequest(messages, 0.7)
      const analysis = this.parseAnalysisResult(result)
      
      this.cache.set(cacheKey, analysis)
      return analysis
    } catch (error) {
      console.error('消费分析失败:', error)
      return this.getDefaultAnalysis(expenses)
    }
  }

  parseAnalysisResult(result) {
    try {
      // 尝试解析数据格式
      const parsed = JSON.parse(result)
      if (parsed.insights && parsed.suggestions) {
        return parsed
      }
    } catch (e) {
      // 数据解析失败，尝试文本解析
    }

    // 文本解析备用方案
    const lines = result.split('\n').filter(line => line.trim())
    const insights = []
    const suggestions = []
    
    let currentSection = null
    
    for (const line of lines) {
      if (line.includes('洞察') || line.includes('insights')) {
        currentSection = 'insights'
      } else if (line.includes('建议') || line.includes('suggestions')) {
        currentSection = 'suggestions'
      } else if (line.trim().startsWith('-') || line.trim().startsWith('•')) {
        const content = line.replace(/^[-•]\s*/, '').trim()
        if (currentSection === 'insights') {
          insights.push(content)
        } else if (currentSection === 'suggestions') {
          suggestions.push(content)
        }
      }
    }

    return {
      insights: insights.length > 0 ? insights : ['消费数据已收集，建议定期回顾支出情况'],
      suggestions: suggestions.length > 0 ? suggestions : ['制定月度预算计划，控制不必要支出']
    }
  }

  getDefaultAnalysis(expenses) {
    const totalAmount = expenses.reduce((sum, exp) => sum + exp.amount, 0)
    const categoryStats = this.calculateCategoryStats(expenses)
    const topCategory = Object.entries(categoryStats)
      .sort(([,a], [,b]) => b.total - a.total)[0]

    return {
      insights: [
        `本期总消费 ${totalAmount.toFixed(2)} 元`,
        `主要支出类别为 ${topCategory ? topCategory[0] : '未分类'}`,
        `平均每笔消费 ${(totalAmount / expenses.length).toFixed(2)} 元`
      ],
      suggestions: [
        '建议设置月度预算限额',
        '关注高频消费类别的支出控制',
        '定期回顾和调整消费习惯'
      ]
    }
  }

  async generateReport(data) {
    const { expenses, period, statistics } = data
    
    const cacheKey = this.generateCacheKey({ type: 'report', period, stats: statistics })
    
    if (this.cache.has(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    const messages = [
      {
        role: 'system',
        content: `你是一个专业的财务报告生成器。基于用户的消费数据生成详细的财务报告。
报告应该包含：
1. 消费概览
2. 分类分析
3. 趋势分析
4. 改进建议

请用专业但易懂的中文撰写，格式清晰。`
      },
      {
        role: 'user',
        content: `请为${period}期间生成财务报告：
总消费：${statistics.totalExpense}元
消费记录：${expenses.length}条
主要分类：${statistics.categoryStats.map(cat => `${cat.name}(${cat.total}元)`).join('、')}

请生成详细的分析报告。`
      }
    ]

    try {
      const result = await this.makeRequest(messages, 0.8)
      this.cache.set(cacheKey, result)
      return result
    } catch (error) {
      console.error('报告生成失败:', error)
      return this.getDefaultReport(data)
    }
  }

  getDefaultReport(data) {
    const { expenses, period, statistics } = data
    
    return `# ${period}消费报告

## 消费概览
本期总消费：${statistics.totalExpense.toFixed(2)}元
消费记录数：${expenses.length}条
平均每笔消费：${(statistics.totalExpense / expenses.length).toFixed(2)}元

## 分类分析
${statistics.categoryStats.map(cat => 
  `- ${cat.name}：${cat.total.toFixed(2)}元 (${((cat.total / statistics.totalExpense) * 100).toFixed(1)}%)`
).join('\n')}

## 改进建议
- 建议制定预算计划，控制支出
- 关注主要消费类别，寻找节省空间
- 定期回顾消费习惯，优化财务管理`
  }

  calculateCategoryStats(expenses) {
    const stats = {}
    
    expenses.forEach(expense => {
      const category = expense.category_name || '未分类'
      if (!stats[category]) {
        stats[category] = { total: 0, count: 0 }
      }
      stats[category].total += expense.amount
      stats[category].count += 1
    })
    
    return stats
  }

  getDefaultCategorySuggestion(description) {
    const desc = description.toLowerCase()
    const keywords = {
      '餐饮': ['吃', '喝', '餐', '饭', '菜', '咖啡', '奶茶', '外卖', '食物', '早餐', '午餐', '晚餐', '零食', '水果'],
      '交通': ['车', '地铁', '公交', '打车', '滴滴', '油费', '停车', '出租车', '高铁', '飞机', '火车'],
      '购物': ['买', '购', '商场', '超市', '淘宝', '京东', '衣服', '鞋子', '化妆品', '日用品', '电子产品'],
      '娱乐': ['电影', '游戏', 'KTV', '旅游', '健身', '运动', '音乐', '演出', '酒吧', '聚会'],
      '医疗': ['医院', '药', '看病', '体检', '牙科', '挂号', '治疗', '检查'],
      '教育': ['学费', '书', '培训', '课程', '学习', '教材', '辅导', '考试'],
      '住房': ['房租', '水电', '物业', '装修', '家具', '房贷', '维修', '清洁']
    }

    for (const [category, words] of Object.entries(keywords)) {
      if (words.some(word => desc.includes(word))) {
        return category
      }
    }
    return '其他'
  }

  clearCache() {
    this.cache.clear()
  }
}

module.exports = AIService